package com.hunt.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hunt.dao.StkLimitMapper;
import com.hunt.model.app.StkLimit;
import com.hunt.model.app.nuggets.*;
import com.hunt.service.app.NuggetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.math.BigDecimal;
import java.util.*;


@Service
public class NuggetsServiceImpl implements NuggetsService {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private StkLimitMapper stkLimitMapper;

    @Override
    public ResultNuggetsVo findHotRank() {

        ResultNuggetsVo nuggetsVo = new ResultNuggetsVo();
        Jedis jedis = null;
        try {
            Integer down = 0;
            Integer down7 = 0;
            Integer down37 = 0;
            Integer down03 = 0;
            Integer noPower = 0;
            Integer max03 = 0;
            Integer max37 = 0;
            Integer max7 = 0;
            Integer max = 0;
            List<HqStockData> maxList = new ArrayList<>();
            List<HqStockData> downList = new ArrayList<>();

            jedis = jedisPool.getResource();
            Map<String, Object> price_limit = new HashMap<>();
            Map<String, String> values = jedis.hgetAll("Real_time_Stock_Data");
            Map<String, String> allBlock = jedis.hgetAll("Block_Info");


            List<String> limitUpList = new ArrayList<>();
            List<String> limitDownList = new ArrayList<>();

            for (StkLimit stkLimit : stkLimitMapper.findAll()) {
                StockPriceLimit stockPriceLimit = new StockPriceLimit();
                stockPriceLimit.setTime(stkLimit.getTrade_date());
                stockPriceLimit.setThscode(stkLimit.getTs_code());
                StockPriceLimitInfo stockPriceLimitInfo = new StockPriceLimitInfo();
                stockPriceLimitInfo.setDownLimit(Float.parseFloat(stkLimit.getDown_limit()));
                stockPriceLimitInfo.setUpperLimit(Float.parseFloat(stkLimit.getUp_limit()));
                stockPriceLimit.setTable(stockPriceLimitInfo);
                price_limit.put(stkLimit.getTs_code(), stockPriceLimit);
            }
             //循环所有带有涨跌指数的股票
            Iterator<Map.Entry<String, Object>> it = price_limit.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                String code = entry.getKey().toLowerCase(Locale.ROOT);
                String stockData = values.get(code);
                if (stockData == null)
                    continue;
                HqStockData hqStockData = JSON.parseObject(stockData, HqStockData.class);
                if (hqStockData.getMsgId().equals("4097"))//排除指数包
                    continue;
                if ("--".equals(hqStockData.getHlPercent()))//排除未开盘情况
                    continue;
                if (hqStockData.getHlPercent()==null){
                   
                    continue;
                }
                float hl = Float.valueOf(hqStockData.getHlPercent().replaceAll("%", ""));
                StockPriceLimit priceLimit = (StockPriceLimit) entry.getValue();
                float newPrice = hqStockData.getNewPrice();
                if (newPrice <= priceLimit.getTable().getDownLimit()){
                    down++;
                    limitDownList.add(priceLimit.getThscode());
                }
                else if (newPrice >= priceLimit.getTable().getUpperLimit()){
                    max++;
                    maxList.add(hqStockData);
                    limitUpList.add(priceLimit.getThscode());
                }
                else if (hl == 0){
                    noPower++;
                }
                else if (hl > 0 && hl < 3){
                    max03++;
                    maxList.add(hqStockData);
                }
                else if (hl >= 3 && hl < 7){
                    max37++;
                    maxList.add(hqStockData);
                }
                else if (hl >= 7 && newPrice < priceLimit.getTable().getUpperLimit()){
                    max7++;
                    maxList.add(hqStockData);
                }
                else if (hl < 0 && hl > -3){
                    down03++;
                }
                else if (hl <= -3 && hl > -7){
                    down37++;
                }
                else if (hl <= -7 && newPrice > priceLimit.getTable().getDownLimit()){
                    down7++;
                }
            }
        List<Integer> groupCount = nuggetsVo.getGroupCount();
        groupCount.clear();
        groupCount.add(down);
        groupCount.add(down7);
        groupCount.add(down37);
        groupCount.add(down03);
        groupCount.add(noPower);
        groupCount.add(max03);
        groupCount.add(max37);
        groupCount.add(max7);
        groupCount.add(max);
        nuggetsVo.setUpCount(max+max7+max37+max03);
        nuggetsVo.setDownCount(down+down7+down37+down03);
        nuggetsVo.setFlatCount(noPower);
//        System.out.println("涨停股票列表：" + limitUpList);
//        System.out.println("跌停股票列表：" + limitDownList);
        //======================================涨跌数计算完毕,板块排名计算开始==========================================

        Set<Map.Entry<String, String>> entries = allBlock.entrySet();
        Iterator<Map.Entry<String, String>> itr = entries.iterator();
        List<HqIndexData> blockList = new ArrayList<>();
        //循环所有板块信息
        while (itr.hasNext()){
            Map.Entry<String, String> entry = itr.next();
            String blockCode = entry.getKey();
            String value = values.get(blockCode);
            if (value == null)
                continue;
            HqIndexData hqIndexData = JSON.parseObject(value, HqIndexData.class);
            if (hqIndexData.getHlPercent().equals("--")){
                continue;
            }
            blockList.add(hqIndexData);
        }
        //循环涨幅排 前5板块和后5板块 封装数据
        List<BlockShow> showBlock = new ArrayList<>();
            System.out.println(blockList.size());
        if (blockList.size() >= 5){
            //获取前5和后5的板块涨幅排行 //hlPercent="--"时需要特殊处理
            Collections.sort(blockList);
            List<HqIndexData> blockListBySort = new ArrayList<>();
            for (int i = 1; i <= 5; i ++){
                blockListBySort.add(blockList.get(blockList.size() - i));
            }
            for (int i = 0; i < 5; i++) {
                blockListBySort.add(blockList.get(i));
            }
            for (HqIndexData block55 : blockListBySort) {
                BlockShow blockShow = new BlockShow();
                blockShow.setBlockCode(block55.getCode());
                blockShow.setBlockHlPercent(block55.getHlPercent());
                BlockInfo blockInfo = JSON.parseObject(allBlock.get(block55.getCode()), BlockInfo.class);
                blockShow.setBlockName(blockInfo.getBlockName());
                //循环板块中的所有股票,根据涨跌幅排序获取最大值 封装到数据中
                Iterator<BlockStock> iterator = blockInfo.getChildList().iterator();
                while (iterator.hasNext()){
                    BlockStock blockStock = iterator.next();
                    String code = blockStock.getCode();
                    String value = values.get(code);
                    if (value == null){
                        //偶遇停盘股票跳过本次循环,并且删除本list中的blockStock对象,防止排序时报错
                        iterator.remove();
                        continue;
                    }
                    String hlPercent = JSON.parseObject(value).getString("hlPercent");
                    if (hlPercent.equals("--")){
                        iterator.remove();
                        continue;
                    }
                    Float preClose = JSON.parseObject(value).getFloat("preClose");
                    blockStock.setPreClose(preClose);
                    blockStock.setCommonsValue(hlPercent);
                }
                List<BlockStock> childList = blockInfo.getChildList();
                Collections.sort(childList);
                if(childList.size()<1){
                    continue;
                }
                BlockStock blockStock = childList.get(childList.size() - 1);
                blockShow.setMaxStockHlPercent(blockStock.getCommonsValue());
                blockShow.setMaxStockName(blockStock.getName());
                showBlock.add(blockShow);
            }
        }
        nuggetsVo.setHlBlocks(showBlock);

        //=======================================板块排名计算完毕,开始获取涨幅前10的数据======================================
        List<UDPercent> upPercents = new ArrayList<>();
//        if (maxList.size() >= 10){
//            Collections.sort(maxList);
//            for (int i = 1; i <= 10; i++) {
//                HqStockData hqStockData = maxList.get(maxList.size()- i);
//                UDPercent udPercent = new UDPercent();
//                udPercent.setCode(hqStockData.getCode());
//                List<String> stock_base_message = jedis.hmget("Stock_Base_Message", hqStockData.getCode());
//                if (stock_base_message.get(0) == null){
//                    continue;
//                }
//                String name = JSON.parseObject(stock_base_message.get(0)).getString("name");
//                udPercent.setCommonsValue(hqStockData.getHlPercent());
//                udPercent.setName(name);
//                udPercent.setNewPrice(hqStockData.getNewPrice());
//                udPercent.setPreClose(hqStockData.getPreClose());
//                upPercents.add(udPercent);
//            }
//        }
            List<BlockStock> lb=findstocksort();
            for(int i=0;i<lb.size();i++){
                UDPercent ud=new UDPercent();
                ud.setCode(lb.get(i).getCode());
                ud.setName(lb.get(i).getName());
                ud.setNewPrice(lb.get(i).getNewPrice());
                ud.setPreClose(lb.get(i).getPreClose());
                ud.setCommonsValue(lb.get(i).getCommonsValue());
                upPercents.add(ud);
            }
        nuggetsVo.setUpPercents(upPercents);
       } catch (Exception e) {
           e.printStackTrace();
       }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return nuggetsVo;
    }

    @Override
    public ResultNuggetsVo findHotRankTwenty() {

        ResultNuggetsVo nuggetsVo = new ResultNuggetsVo();
        Jedis jedis = null;
        try {
            Integer down = 0;
            Integer down7 = 0;
            Integer down37 = 0;
            Integer down03 = 0;
            Integer noPower = 0;
            Integer max03 = 0;
            Integer max37 = 0;
            Integer max7 = 0;
            Integer max = 0;
            List<HqStockData> maxList = new ArrayList<>();
            List<HqStockData> downList = new ArrayList<>();

            jedis = jedisPool.getResource();
            Map<String, Object> price_limit = new HashMap<>();
            Map<String, String> values = jedis.hgetAll("Real_time_Stock_Data");
            Map<String, String> allBlock = jedis.hgetAll("Block_Info");


            List<String> limitUpList = new ArrayList<>();
            List<String> limitDownList = new ArrayList<>();

            for (StkLimit stkLimit : stkLimitMapper.findAll()) {
                StockPriceLimit stockPriceLimit = new StockPriceLimit();
                stockPriceLimit.setTime(stkLimit.getTrade_date());
                stockPriceLimit.setThscode(stkLimit.getTs_code());
                StockPriceLimitInfo stockPriceLimitInfo = new StockPriceLimitInfo();
                stockPriceLimitInfo.setDownLimit(Float.parseFloat(stkLimit.getDown_limit()));
                stockPriceLimitInfo.setUpperLimit(Float.parseFloat(stkLimit.getUp_limit()));
                stockPriceLimit.setTable(stockPriceLimitInfo);
                price_limit.put(stkLimit.getTs_code(), stockPriceLimit);
            }
            //循环所有带有涨跌指数的股票
            Iterator<Map.Entry<String, Object>> it = price_limit.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                String code = entry.getKey().toLowerCase(Locale.ROOT);
                String stockData = values.get(code);
                if (stockData == null)
                    continue;
                HqStockData hqStockData = JSON.parseObject(stockData, HqStockData.class);
                if (hqStockData.getMsgId().equals("4097"))//排除指数包
                    continue;
                if ("--".equals(hqStockData.getHlPercent()))//排除未开盘情况
                    continue;
                if (hqStockData.getHlPercent()==null){

                    continue;
                }
                float hl = Float.valueOf(hqStockData.getHlPercent().replaceAll("%", ""));
                StockPriceLimit priceLimit = (StockPriceLimit) entry.getValue();
                float newPrice = hqStockData.getNewPrice();
                if (newPrice <= priceLimit.getTable().getDownLimit()){
                    down++;
                    limitDownList.add(priceLimit.getThscode());
                }
                else if (newPrice >= priceLimit.getTable().getUpperLimit()){
                    max++;
                    maxList.add(hqStockData);
                    limitUpList.add(priceLimit.getThscode());
                }
                else if (hl == 0){
                    noPower++;
                }
                else if (hl > 0 && hl < 3){
                    max03++;
                    maxList.add(hqStockData);
                }
                else if (hl >= 3 && hl < 7){
                    max37++;
                    maxList.add(hqStockData);
                }
                else if (hl >= 7 && newPrice < priceLimit.getTable().getUpperLimit()){
                    max7++;
                    maxList.add(hqStockData);
                }
                else if (hl < 0 && hl > -3){
                    down03++;
                }
                else if (hl <= -3 && hl > -7){
                    down37++;
                }
                else if (hl <= -7 && newPrice > priceLimit.getTable().getDownLimit()){
                    down7++;
                }
            }
            List<Integer> groupCount = nuggetsVo.getGroupCount();
            groupCount.clear();
            groupCount.add(down);
            groupCount.add(down7);
            groupCount.add(down37);
            groupCount.add(down03);
            groupCount.add(noPower);
            groupCount.add(max03);
            groupCount.add(max37);
            groupCount.add(max7);
            groupCount.add(max);
            nuggetsVo.setUpCount(max+max7+max37+max03);
            nuggetsVo.setDownCount(down+down7+down37+down03);
            nuggetsVo.setFlatCount(noPower);
            //======================================涨跌数计算完毕,板块排名计算开始==========================================

            Set<Map.Entry<String, String>> entries = allBlock.entrySet();
            Iterator<Map.Entry<String, String>> itr = entries.iterator();
            List<HqIndexData> blockList = new ArrayList<>();
            //循环所有板块信息
            while (itr.hasNext()){
                Map.Entry<String, String> entry = itr.next();
                String blockCode = entry.getKey();
                String value = values.get(blockCode);
                if (value == null)
                    continue;
                HqIndexData hqIndexData = JSON.parseObject(value, HqIndexData.class);
                if (hqIndexData.getHlPercent().equals("--")){
                    continue;
                }
                blockList.add(hqIndexData);
            }
            //循环涨幅排 前5板块和后5板块 封装数据
            List<BlockShow> showBlock = new ArrayList<>();
            if (blockList.size() >= 10){
                //获取前5和后5的板块涨幅排行 //hlPercent="--"时需要特殊处理
                Collections.sort(blockList);
                List<HqIndexData> blockListBySort = new ArrayList<>();
                for (int i = 1; i <= 10; i ++){
                    blockListBySort.add(blockList.get(blockList.size() - i));
                }
                for (int i = 0; i <10; i++) {
                    blockListBySort.add(blockList.get(i));
                }
                for (HqIndexData block55 : blockListBySort) {
                    BlockShow blockShow = new BlockShow();
                    blockShow.setBlockCode(block55.getCode());
                    blockShow.setBlockHlPercent(block55.getHlPercent());
                    BlockInfo blockInfo = JSON.parseObject(allBlock.get(block55.getCode()), BlockInfo.class);
                    blockShow.setBlockName(blockInfo.getBlockName());
                    //循环板块中的所有股票,根据涨跌幅排序获取最大值 封装到数据中
                    Iterator<BlockStock> iterator = blockInfo.getChildList().iterator();
                    while (iterator.hasNext()){
                        BlockStock blockStock = iterator.next();
                        String code = blockStock.getCode();
                        String value = values.get(code);
                        if (value == null){
                            //偶遇停盘股票跳过本次循环,并且删除本list中的blockStock对象,防止排序时报错
                            iterator.remove();
                            continue;
                        }
                        String hlPercent = JSON.parseObject(value).getString("hlPercent");
                        if (hlPercent.equals("--")){
                            iterator.remove();
                            continue;
                        }
                        Float preClose = JSON.parseObject(value).getFloat("preClose");
                        blockStock.setPreClose(preClose);
                        blockStock.setCommonsValue(hlPercent);
                    }
                    List<BlockStock> childList = blockInfo.getChildList();
                    Collections.sort(childList);
                    if(childList.size()<1){
                        continue;
                    }
                    BlockStock blockStock = childList.get(childList.size() - 1);
                    blockShow.setMaxStockHlPercent(blockStock.getCommonsValue());
                    blockShow.setMaxStockName(blockStock.getName());
                    showBlock.add(blockShow);
                }
            }
            nuggetsVo.setHlBlocks(showBlock);

            //=======================================板块排名计算完毕,开始获取涨幅前10的数据======================================
            List<UDPercent> upPercents = new ArrayList<>();
            List<BlockStock> lb=findstocksort();
            for(int i=0;i<lb.size();i++){
                UDPercent ud=new UDPercent();
                ud.setCode(lb.get(i).getCode());
                ud.setName(lb.get(i).getName());
                ud.setNewPrice(lb.get(i).getNewPrice());
                ud.setPreClose(lb.get(i).getPreClose());
                ud.setCommonsValue(lb.get(i).getCommonsValue());
                upPercents.add(ud);
            }
            nuggetsVo.setUpPercents(upPercents);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return nuggetsVo;
    }

    /**
     * 获取上证指数，深证指数，创业板指数分别的上涨，下跌，平盘家数量
     */
    @Override
    public ResultNuggetsVo findUpsDownsByIndexType(int indexType){
        ResultNuggetsVo nuggetsVo = new ResultNuggetsVo();
        Jedis jedis = null;
        try{
            Integer max = 0;
            Integer noPower = 0;
            Integer down = 0;

            jedis = jedisPool.getResource();
            Map<String, Object> price_limit = new HashMap<>();
            Map<String, String> values = jedis.hgetAll("Real_time_Stock_Data");

            for (StkLimit stkLimit : stkLimitMapper.findAll()) {
                StockPriceLimit stockPriceLimit = new StockPriceLimit();
                stockPriceLimit.setTime(stkLimit.getTrade_date());
                stockPriceLimit.setThscode(stkLimit.getTs_code());
                StockPriceLimitInfo stockPriceLimitInfo = new StockPriceLimitInfo();
                stockPriceLimitInfo.setDownLimit(Float.parseFloat(stkLimit.getDown_limit()));
                stockPriceLimitInfo.setUpperLimit(Float.parseFloat(stkLimit.getUp_limit()));
                stockPriceLimit.setTable(stockPriceLimitInfo);
                price_limit.put(stkLimit.getTs_code(), stockPriceLimit);
            }
            //循环所有带有涨跌指数的股票
            Iterator<Map.Entry<String, Object>> it = price_limit.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                String code = entry.getKey().toLowerCase(Locale.ROOT);
                String stockData = values.get(code);
                if (stockData == null)
                    continue;
                HqStockData hqStockData = JSON.parseObject(stockData, HqStockData.class);
                if (hqStockData.getMsgId().equals("4097"))//排除指数包
                    continue;
                if ("--".equals(hqStockData.getHlPercent()))//排除未开盘情况
                    continue;
                if (hqStockData.getHlPercent()==null){
                    continue;
                }
                float hl = Float.valueOf(hqStockData.getHlPercent().replaceAll("%", ""));
                StockPriceLimit priceLimit = (StockPriceLimit) entry.getValue();
                float newPrice = hqStockData.getNewPrice();

                if(!code.isEmpty()){
                    switch (indexType){
                        case 0:
                            if (code.substring(code.length() -2).equals("sh")){
                                if (newPrice <= priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                                else if (newPrice >= priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl == 0){
                                    noPower++;
                                }
                                else if (hl > 0 && hl < 3){
                                    max++;
                                }
                                else if (hl >= 3 && hl < 7){
                                    max++;
                                }
                                else if (hl >= 7 && newPrice < priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl < 0 && hl > -3){
                                    down++;
                                }
                                else if (hl <= -3 && hl > -7){
                                    down++;
                                }
                                else if (hl <= -7 && newPrice > priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                            }
                            break;
                        case 1:
                            if (code.substring(code.length() -2).equals("sz")){
                                if (newPrice <= priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                                else if (newPrice >= priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl == 0){
                                    noPower++;
                                }
                                else if (hl > 0 && hl < 3){
                                    max++;
                                }
                                else if (hl >= 3 && hl < 7){
                                    max++;
                                }
                                else if (hl >= 7 && newPrice < priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl < 0 && hl > -3){
                                    down++;
                                }
                                else if (hl <= -3 && hl > -7){
                                    down++;
                                }
                                else if (hl <= -7 && newPrice > priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                            }
                            break;
                        case 2:
                            if (code.startsWith("3")){
                                if (newPrice <= priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                                else if (newPrice >= priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl == 0){
                                    noPower++;
                                }
                                else if (hl > 0 && hl < 3){
                                    max++;
                                }
                                else if (hl >= 3 && hl < 7){
                                    max++;
                                }
                                else if (hl >= 7 && newPrice < priceLimit.getTable().getUpperLimit()){
                                    max++;
                                }
                                else if (hl < 0 && hl > -3){
                                    down++;
                                }
                                else if (hl <= -3 && hl > -7){
                                    down++;
                                }
                                else if (hl <= -7 && newPrice > priceLimit.getTable().getDownLimit()){
                                    down++;
                                }
                            }
                            break;
                    }
                }
            }
            nuggetsVo.setUpCount(max);
            nuggetsVo.setDownCount(down);
            nuggetsVo.setFlatCount(noPower);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return nuggetsVo;
    }

    /**
     * 获取更多概念板块排行
     * @param sort
     * @param point
     * @param limit
     * @return
     */
    @Override
    public List<BlockShow> findMoreBlockSort(int sort,int point,int limit) {
        Jedis jedis = null;
        List<BlockShow> blockShows = new ArrayList<>();
        try {
            //有缓存时处理
            jedis = jedisPool.getResource();
            String blockList = jedis.get("Block_Sort");
            if (blockList != null && !blockList.equals("")){
                List<BlockShow> blockShowsList = JSONArray.parseArray(blockList, BlockShow.class);
                if (point>=blockShowsList.size()){
                    point = blockShowsList.size();
                }
                if (limit>=blockShowsList.size()){
                    limit = blockShowsList.size();
                }
                if (sort == 1){
                    Collections.reverse(blockShowsList);
                    List<BlockShow> bs = blockShowsList.subList(point, limit);
                    return bs;
                }else{
                    List<BlockShow> bs = blockShowsList.subList(point, limit);
                    return bs;
                }
            }
            //没有缓存时处理
            Map<String, String> allBlock = jedis.hgetAll("Block_Info");
            Map<String, String> realTimeData = jedis.hgetAll("Real_time_Stock_Data");
            Set<Map.Entry<String, String>> allBlockEntries = allBlock.entrySet();
            Iterator<Map.Entry<String, String>> iterator = allBlockEntries.iterator();
            while (iterator.hasNext()){
                Map.Entry<String, String> entry = iterator.next();
                String blockCode = JSON.parseObject(entry.getValue()).getString("blockCode");
                String blockName = JSON.parseObject(entry.getValue()).getString("blockName");
                String hlPercent = null == realTimeData.get(blockCode) ?
                        "--" : JSON.parseObject(realTimeData.get(blockCode)).getString("hlPercent");
                if (hlPercent.equals("--")){
                    iterator.remove();
                    continue;
                }
                BlockShow blockShow = new BlockShow();
                blockShow.setBlockCode(blockCode);
                blockShow.setBlockName(blockName);
                blockShow.setBlockHlPercent(hlPercent);
                blockShows.add(blockShow);
            }
            Collections.sort(blockShows);
            jedis.set("Block_Sort",JSON.toJSONString(blockShows));
            jedis.expire("Block_Sort",30);

            if (point >= blockShows.size()){
                point = blockShows.size();
            }
            if (limit >= blockShows.size()){
                limit = blockShows.size();
            }

            if (sort == 1){
                Collections.reverse(blockShows);
                return blockShows.subList(point,limit);
            }else{
                return blockShows.subList(point,limit);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis!=null){
                jedis.close();
            }
        }
        return blockShows;
    }

    /**
     * 查询某概念板块内所有股票/根据涨跌幅排序
     * @param blockCode
     * @param sort
     * @param point
     * @param limit
     * @return
     */
    @Override
    public BlockInfo findStockListWithinBlock(String blockCode, int sort, int point, int limit) {
        Jedis jedis = null;
        BlockInfo blockInfo = null;
        try {
            //有缓存时处理
            jedis = jedisPool.getResource();
            Map<String, String> realTimeStockData = jedis.hgetAll("Real_time_Stock_Data");
            String s = jedis.get("Block_Stock_Sort:" + blockCode);
            if (s != null && !s.equals("")){
                blockInfo = JSON.parseObject(s, BlockInfo.class);
                List<BlockStock> childList = blockInfo.getChildList();
                if (point >= childList.size()){
                    point = childList.size();
                }
                if (limit>=childList.size()){
                    limit = childList.size();
                }
                if (sort == 1){
                    Collections.reverse(childList);
                    List<BlockStock> blockStocks = childList.subList(point, limit);
                    blockInfo.setChildList(blockStocks);
                    return blockInfo;
                }else{
                    List<BlockStock> blockStocks = childList.subList(point, limit);
                    blockInfo.setChildList(blockStocks);
                    return blockInfo;
                }
            }
            List<String> block_info = jedis.hmget("Block_Info", blockCode);
            blockInfo = JSON.parseObject(block_info.get(0), BlockInfo.class);
            if (blockInfo == null){
                return new BlockInfo();
            }
            //没有缓存时处理
            //获取板块内所有股票
            List<BlockStock> childList = blockInfo.getChildList();
            Iterator<BlockStock> it = childList.iterator();
            while (it.hasNext()){
                BlockStock blockStock = it.next();
                String value = realTimeStockData.get(blockStock.getCode());
                if (value == null){
                    it.remove();
                    continue;
                }
                JSONObject json = JSON.parseObject(value);
                String hlPercent = json.getString("hlPercent");
                Float newPrice = json.getFloat("newPrice");
                String change = json.getString("change");
                Float preClose = json.getFloat("preClose");
                if (hlPercent.equals("--") || newPrice == 0 || change.equals("--")){
                    it.remove();
                    continue;
                }
                blockStock.setChange(change);
                blockStock.setCommonsValue(hlPercent);
                blockStock.setNewPrice(newPrice);
                blockStock.setPreClose(preClose);
            }
            Collections.sort(childList);
            jedis.set("Block_Stock_Sort:" + blockCode,JSON.toJSONString(blockInfo));
            jedis.expire("Block_Stock_Sort:" + blockCode,60);

            if (point >= childList.size()){
                point = childList.size();
            }
            if (limit >= childList.size()){
                limit = childList.size();
            }
            if (sort == 1){
                Collections.reverse(childList);
                List<BlockStock> blockStocks = childList.subList(point,limit);
                blockInfo.setChildList(blockStocks);
            }else{
                List<BlockStock> blockStocks = childList.subList(point,limit);
                blockInfo.setChildList(blockStocks);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return blockInfo;
    }

    /**
     * 查询涨跌幅股票排行
     * @param sort
     * @param position
     * @param size
     * @return
     */
    @Override
    public List<BlockStock> findHlPercentRankList(int sort,int position,int size,int type) {

        Jedis jedis = null;
        List<BlockStock> stockListBySort = new ArrayList<>();
        List<CommonsStockInfo> stockListInfo;
        try {
            jedis = jedisPool.getResource();
            String s = jedis.get("Stock_Info_Sort");
            //从redis中获取涨跌幅排行的结果集
            if (s != null && !s.equals("")){
                stockListInfo = JSONArray.parseArray(s, CommonsStockInfo.class);
            //缓存过期后重新计算结果集
            }else{
                stockListInfo = new ArrayList<>();
                Map<String, String> stockBaseMessage = jedis.hgetAll("Stock_Base_Message");
                Map<String, String> realTimeStock = jedis.hgetAll("Real_time_Stock_Data");
                Iterator<Map.Entry<String, String>> sbm = stockBaseMessage.entrySet().iterator();
                while (sbm.hasNext()){
                    Map.Entry<String, String> entry = sbm.next();
                    String value = realTimeStock.get(entry.getKey());
                    if (value == null){
                        continue;
                    }
                    HqStockData hqStockData = JSON.parseObject(value, HqStockData.class);
                    if (hqStockData.getHlPercent().equals("--") || hqStockData.getChange().equals("--")){
                        continue;
                    }
                    String name = JSON.parseObject(entry.getValue()).getString("name");
                    String floatShares = JSON.parseObject(stockBaseMessage.get(hqStockData.getCode())).getString("floatShares");
                    CommonsStockInfo info = new CommonsStockInfo();
                    info.setCode(hqStockData.getCode());
                    info.setName(name);
                    info.setNewPrice(hqStockData.getNewPrice());
                    info.setHlPercent(hqStockData.getHlPercent());
                    info.setChange(hqStockData.getChange());
                  try {
                      double m1=hqStockData.getVol();
                      double m2=Double.valueOf(floatShares);
                      info.setTurnoverRate(new BigDecimal(m1/m2).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                  }catch (Exception e){
                      info.setTurnoverRate("0.00");
                  }
                    info.setVol(hqStockData.getVol());
                    info.setPreClose(hqStockData.getPreClose());
                    stockListInfo.add(info);
                }
                jedis.set("Stock_Info_Sort",JSON.toJSONString(stockListInfo));
                jedis.expire("Stock_Info_Sort",60);
            }

            //防止角标越界的操作
            if (position>=stockListInfo.size())
                position=stockListInfo.size();
            if (size>=stockListInfo.size())
                size=stockListInfo.size();

            //返回换手率排序
            if (type == 1){
                for (CommonsStockInfo info : stockListInfo) {
                    BlockStock result = new BlockStock(info);
                    result.setCommonsValue(info.getTurnoverRate()+"%");
                    stockListBySort.add(result);
                }
                Collections.sort(stockListBySort);
                if (sort == 1){
                    Collections.reverse(stockListBySort);
                }
            //返回5分钟涨跌幅排序（例如 9.56-9.51/9.51)（还没有改)
            }else if (type == 2){
                Map<String, String> FiveMap = jedis.hgetAll("Five_Minute_Stock_HlPercent");
                for (CommonsStockInfo info : stockListInfo) {
                    BlockStock commonsSortResult = new BlockStock(info);
                    String fiveHlPercent=FiveMap.get(info.getCode());
                    if(null!=fiveHlPercent){
                        commonsSortResult.setCommonsValue(FiveMap.get(info.getCode()));
                    }
                    else {
                        commonsSortResult.setCommonsValue("0.0%");
                    }
                    stockListBySort.add(commonsSortResult);
                }
                Collections.sort(stockListBySort);
                if (sort == 1){
                    Collections.reverse(stockListBySort);
                }
            }
            else if (type == 3){
                for (CommonsStockInfo info : stockListInfo) {
                    BlockStock commonsSortResult = new BlockStock(info);
                    commonsSortResult.setCommonsValue(String.valueOf(info.getVol()));
                    stockListBySort.add(commonsSortResult);
                }
                Collections.sort(stockListBySort);
                if (sort == 1){
                    Collections.reverse(stockListBySort);
                }
            }
            //返回涨跌幅排序
            else{
                for (CommonsStockInfo info : stockListInfo) {
                    BlockStock result = new BlockStock(info);
                    result.setCommonsValue(info.getHlPercent());
                    stockListBySort.add(result);
                }
                Collections.sort(stockListBySort);
                if (sort == 1){
                    Collections.reverse(stockListBySort);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return stockListBySort.subList(position,size);
    }
    private List<BlockStock> findstocksort(){
        Jedis jedis = null;
        List<BlockStock> stockListBySort = new ArrayList<>();
        List<CommonsStockInfo> stockListInfo;
        try {
            jedis = jedisPool.getResource();
            String s = jedis.get("Stock_Info_Sort");
            //从redis中获取涨跌幅排行的结果集
            if (s != null && !s.equals("")){
                stockListInfo = JSONArray.parseArray(s, CommonsStockInfo.class);
                //缓存过期后重新计算结果集
            }else{
                stockListInfo = new ArrayList<>();
                Map<String, String> stockBaseMessage = jedis.hgetAll("Stock_Base_Message");
                Map<String, String> realTimeStock = jedis.hgetAll("Real_time_Stock_Data");
                Iterator<Map.Entry<String, String>> sbm = stockBaseMessage.entrySet().iterator();
                while (sbm.hasNext()){
                    Map.Entry<String, String> entry = sbm.next();
                    String value = realTimeStock.get(entry.getKey());
                    if (value == null){
                        continue;
                    }
                    HqStockData hqStockData = JSON.parseObject(value, HqStockData.class);
                    if (hqStockData.getHlPercent()==null || hqStockData.getChange()==null){
                        continue;
                    }
                    if (hqStockData.getHlPercent().equals("--") || hqStockData.getChange().equals("--")){
                        continue;
                    }
                    String name = JSON.parseObject(entry.getValue()).getString("name");
                    String floatShares = JSON.parseObject(stockBaseMessage.get(hqStockData.getCode())).getString("floatShares");
                    CommonsStockInfo info = new CommonsStockInfo();
                    info.setCode(hqStockData.getCode());
                    info.setName(name);
                    info.setNewPrice(hqStockData.getNewPrice());
                    info.setHlPercent(hqStockData.getHlPercent());
                    info.setChange(hqStockData.getChange());
                    try {
                        info.setTurnoverRate(new BigDecimal(hqStockData.getVol()/Float.valueOf(floatShares)*10000).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    }
                   catch ( Exception e){
                        info.setTurnoverRate("0.00");
                    }
                    info.setVol(hqStockData.getVol());
                    info.setPreClose(hqStockData.getPreClose());
                    stockListInfo.add(info);
                }
            }
                for (CommonsStockInfo info : stockListInfo) {
                    BlockStock result = new BlockStock(info);
                    result.setCommonsValue(info.getHlPercent());
                    stockListBySort.add(result);
                }
                Collections.sort(stockListBySort);
                Collections.reverse(stockListBySort);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return stockListBySort.subList(0,10);
    }
}
